<template>
	<view class="profile-container">
		<!-- 头部导航 -->
		<view class="header">
			<view class="nav-left" @click="goBack">
				<text class="back-icon">←</text>
			</view>
			<view class="nav-title">
				<text class="title-text">个人资料</text>
				</view>
			<view class="nav-right">
				<text class="menu-icon">⋯</text>
				<text class="menu-icon">─</text>
				<text class="eye-icon">👁</text>
			</view>
		</view>

		<!-- 信息列表 -->
		<view class="info-list">
			<!-- 头像 -->
			<view class="info-item" @click="editAvatar">
				<view class="item-left">
					<text class="item-label">头像</text>
				</view>
				<view class="item-right">
					<image class="avatar-image" :src="userAvatar" mode="aspectFill" />
					<text class="arrow-icon">></text>
				</view>
		</view>

			<!-- 昵称 -->
			<view class="info-item" @click="editNickname">
				<view class="item-left">
					<text class="item-label">昵称</text>
				</view>
				<view class="item-right">
					<input 
						class="nickname-input" 
						v-model="nickname" 
						placeholder="请输入昵称"
						:disabled="!isEditingNickname"
						@blur="saveNickname"
					/>
					<text class="arrow-icon">></text>
			</view>
		</view>

			<!-- 学号 -->
			<view class="info-item" @click="editStudentId">
				<view class="item-left">
					<text class="item-label">学号</text>
				</view>
				<view class="item-right">
					<input 
						class="student-id-input" 
						v-model="studentId" 
						placeholder="请输入学号"
						:disabled="!isEditingStudentId"
						@blur="saveStudentId"
					/>
					<text class="arrow-icon">></text>
			</view>
		</view>

			<!-- 认证状态 -->
			<view class="info-item" @click="editCertification">
				<view class="item-left">
					<text class="item-label">认证状态</text>
				</view>
				<view class="item-right">
					<text class="certification-status">{{ certificationStatus }}</text>
					<text class="arrow-icon">></text>
				</view>
				</view>
			</view>

		<!-- 提交修改按钮 -->
		<view class="submit-section">
			<button class="submit-btn" @click="submitChanges">
				提交修改
			</button>
		</view>

		<!-- 头像选择弹窗 -->
		<sar-action-sheet 
			v-model:visible="avatarSheetVisible" 
			title="选择头像" 
			:item-list="avatarOptions" 
			@select="handleAvatarSelect" 
		/>

		<!-- 认证状态弹窗 -->
		<sar-action-sheet 
			v-model:visible="certificationSheetVisible" 
			title="认证状态" 
			:item-list="certificationOptions" 
			@select="handleCertificationSelect" 
		/>
	</view>
</template>

<script setup lang="ts">
	import { ref, computed, onMounted } from 'vue'
	import { useUserStore } from '@/stores'
	import type { ActionSheetItem } from 'sard-uniapp'

	const userStore = useUserStore()

	// 响应式数据
	const nickname = ref('')
	const studentId = ref('')
	const isEditingNickname = ref(false)
	const isEditingStudentId = ref(false)
	const avatarSheetVisible = ref(false)
	const certificationSheetVisible = ref(false)

	// 头像选项
	const avatarOptions = ref([
		{ name: '从相册选择', value: 'gallery' },
		{ name: '拍照', value: 'camera' },
		{ name: '使用默认头像', value: 'default' }
	] as any[])

	// 认证状态选项
	const certificationOptions = ref([
		{ name: '未认证', value: 'uncertified' },
		{ name: '已认证', value: 'certified' },
		{ name: '认证中', value: 'certifying' }
	] as any[])

	// 计算属性
	const userAvatar = computed(() => {
		return userStore.userInfo?.avatar || '/static/app/icons/120x120.png'
	})

	const certificationStatus = computed(() => {
		// 从本地存储读取认证状态
		const status = uni.getStorageSync('certificationStatus')
		switch (status) {
			case 'applying':
				return '申请中'
			case 'certified':
				return '已认证'
			case 'rejected':
				return '认证失败'
			default:
				return '未认证'
		}
	})

	// 方法
	const goBack = () => {
		uni.navigateBack()
	}

	const editAvatar = () => {
		avatarSheetVisible.value = true
	}

	const editNickname = () => {
		isEditingNickname.value = true
		// 聚焦输入框
		nextTick(() => {
			const input = document.querySelector('.nickname-input') as HTMLInputElement
			if (input) {
				input.focus()
			}
		})
	}

	const editCertification = () => {
		// 跳转到认证页面
		uni.navigateTo({
			url: '/pages/my/certification/cert',
			success: () => {
				console.log('跳转到认证页面成功')
			},
			fail: (err) => {
				console.error('跳转到认证页面失败:', err)
				uni.$tao?.toast?.('页面跳转失败')
			}
		})
	}

	const saveNickname = () => {
		isEditingNickname.value = false
		// 保存昵称到store
		if (userStore.userInfo) {
			userStore.setUserInfo({
				...userStore.userInfo,
				nickName: nickname.value
			})
		}
	}

	const editStudentId = () => {
		isEditingStudentId.value = true
		// 聚焦输入框
		nextTick(() => {
			const input = document.querySelector('.student-id-input') as HTMLInputElement
			if (input) {
				input.focus()
			}
		})
	}

	const saveStudentId = () => {
		isEditingStudentId.value = false
		// 保存学号到本地存储
		uni.setStorageSync('userStudentId', studentId.value)
	}

	const handleAvatarSelect = (item: any) => {
		console.log('选择头像方式:', item)
		
		if (item.value === 'gallery') {
			// 从相册选择
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album'],
				success: (res) => {
					console.log('选择图片成功:', res)
					const tempFilePath = res.tempFilePaths[0]
					
					// 更新头像
					if (userStore.userInfo) {
						userStore.setUserInfo({
							...userStore.userInfo,
							avatar: tempFilePath
						})
					}
					
					// 保存到本地存储
					uni.setStorageSync('userAvatar', tempFilePath)
					
					// 发送头像更新事件
					uni.$emit('avatarUpdated', tempFilePath)
					
					uni.$tao?.toast?.('头像更新成功')
				},
				fail: (err) => {
					console.error('选择图片失败:', err)
					uni.$tao?.toast?.('选择图片失败')
				}
			})
		} else if (item.value === 'camera') {
			// 拍照
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['camera'],
				success: (res) => {
					console.log('拍照成功:', res)
					const tempFilePath = res.tempFilePaths[0]
					
					// 更新头像
				if (userStore.userInfo) {
					userStore.setUserInfo({
						...userStore.userInfo,
							avatar: tempFilePath
						})
					}
					
					// 保存到本地存储
					uni.setStorageSync('userAvatar', tempFilePath)
				
				// 发送头像更新事件
					uni.$emit('avatarUpdated', tempFilePath)
					
					uni.$tao?.toast?.('头像更新成功')
				},
				fail: (err) => {
					console.error('拍照失败:', err)
					uni.$tao?.toast?.('拍照失败')
				}
			})
		} else if (item.value === 'default') {
			// 使用默认头像
			const defaultAvatar = '/static/app/icons/120x120.png'
			
			// 更新头像
							if (userStore.userInfo) {
								userStore.setUserInfo({
									...userStore.userInfo,
					avatar: defaultAvatar
				})
			}
			
			// 保存到本地存储
			uni.setStorageSync('userAvatar', defaultAvatar)
			
			// 发送头像更新事件
			uni.$emit('avatarUpdated', defaultAvatar)
			
			uni.$tao?.toast?.('已设置为默认头像')
		}
	}

	const handleCertificationSelect = (item: any) => {
		console.log('选择认证状态:', item)
		// 这里可以根据选择更新认证状态
		uni.$tao?.toast?.('认证功能开发中')
	}

	const submitChanges = () => {
		// 保存昵称到store
		if (userStore.userInfo) {
			userStore.setUserInfo({
				...userStore.userInfo,
				nickName: nickname.value
			})
		}
		
		// 保存学号到本地存储
		uni.setStorageSync('userStudentId', studentId.value)
		
		// 提交所有修改
		console.log('提交修改:', {
			nickname: nickname.value,
			studentId: studentId.value,
			avatar: userAvatar.value,
			certification: certificationStatus.value
		})
		
		uni.$tao?.toast?.('修改已提交')
		
		// 延迟跳转到my页面
		setTimeout(() => {
			uni.switchTab({
				url: '/pages/my/my'
			})
		}, 1500)
	}

	// 生命周期
	onMounted(() => {
		// 初始化昵称和学号
		nickname.value = userStore.userInfo?.nickName || ''
		studentId.value = uni.getStorageSync('userStudentId') || ''
	})
</script>

<style lang="scss" scoped>
	.profile-container {
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	// 头部导航
	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 30rpx;
		background-color: #fff;
		border-bottom: 1rpx solid #e5e5e5;
	}

	.nav-left, .nav-right {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}
	
	.back-icon {
		font-size: 36rpx;
		color: #333;
	}

	.nav-title {
		flex: 1;
		text-align: center;
	}

	.title-text {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.menu-icon, .eye-icon {
		font-size: 28rpx;
		color: #666;
	}

	// 信息列表
	.info-list {
		margin-top: 20rpx;
		background-color: #fff;
	}

	.info-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
		transition: background-color 0.2s ease;

		&:active {
			background-color: #f8f8f8;
		}

		&:last-child {
			border-bottom: none;
		}
	}

	.item-left {
		flex: 1;
	}

	.item-label {
		font-size: 30rpx;
		color: #333;
	}

	.item-right {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.avatar-image {
		width: 80rpx;
		height: 80rpx;
		border-radius: 40rpx;
		background-color: #f0f0f0;
	}

	.nickname-input, .student-id-input {
		flex: 1;
		font-size: 30rpx;
		color: #333;
		text-align: right;
		border: none;
		background: transparent;
		outline: none;

		&:disabled {
			color: #999;
		}
	}

	.certification-status {
		font-size: 30rpx;
		color: #666;
	}

	.arrow-icon {
		font-size: 24rpx;
		color: #ccc;
	}

	// 提交按钮
	.submit-section {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 30rpx;
		background-color: #fff;
		border-top: 1rpx solid #e5e5e5;
	}

	.submit-btn {
		width: 100%;
		height: 88rpx;
		background-color: #ff4757;
		color: #fff;
		font-size: 32rpx;
		font-weight: bold;
		border: none;
		border-radius: 44rpx;
		transition: background-color 0.2s ease;

		&:active {
			background-color: #ff3742;
		}
	}
</style>